﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Quartz;

namespace MvcApplication1
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }
        IScheduler sched;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            // 默认情况下对 Entity Framework 使用 LocalDB
            Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            log4net.Config.XmlConfigurator.Configure();
            string cronExpr = ConfigurationManager.AppSettings["cronExpr"];
            ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory();
            sched = sf.GetScheduler();

            IDictionary<IJobDetail, IList<ITrigger>> scheduleJobs = new Dictionary<IJobDetail, IList<ITrigger>>();

            scheduleJobs.Add(JobBuilder.Create<CallbackJob>()
                 .WithIdentity("job1", "group1")
                 .Build(),
               new List<ITrigger> {(ICronTrigger)TriggerBuilder.Create()
               .WithIdentity("trigger1", "group1")
               .WithCronSchedule(cronExpr)
               .Build()
               });

            scheduleJobs.Add(JobBuilder.Create<CallbackJob2>()
            .WithIdentity("job1", "group2")
            .Build(),
          new List<ITrigger> {(ICronTrigger)TriggerBuilder.Create()
               .WithIdentity("trigger1", "group2")
               .WithCronSchedule(cronExpr)
               .Build()
               });


            sched.ScheduleJobs(scheduleJobs, true);
            sched.Start();
        }


        protected void Application_End(object sender, EventArgs e)
        {
            //   在应用程序关闭时运行的代码
            if (sched != null)
            {
                sched.Shutdown(true);
            }
        }
    }
}